const express = require('express');
const path = require('path');
const fs = require('fs');
const curlconverter = require('curlconverter');

const app = express();
const PORT = 3000;

// 中间件
app.use(express.json());
app.use(express.static(path.join(__dirname)));

// API 路由：转换 cURL 命令
app.post('/api/convert', async (req, res) => {
    try {
        const { curlCommand, language } = req.body;
        
        if (!curlCommand || !language) {
            return res.status(400).json({ 
                error: '缺少必要参数：curlCommand 和 language' 
            });
        }
        
        // 语言映射
        const languageMap = {
            'python': 'toPython',
            'javascript': 'toJavaScript',
            'node': 'toNodejs',
            'go': 'toGo',
            'java': 'toJava',
            'php': 'toPhp',
            'csharp': 'toCsharp',
            'ruby': 'toRuby',
            'rust': 'toRust',
            'swift': 'toSwift',
            'kotlin': 'toKotlin',
            'dart': 'toDart',
            'r': 'toR',
            'powershell': 'toPowershell',
            'http': 'toHttp',
            'wget': 'toWget'
        };
        
        const converterFunction = languageMap[language];
        if (!converterFunction) {
            return res.status(400).json({ 
                error: `不支持的语言: ${language}` 
            });
        }
        
        // 执行转换
        const result = curlconverter[converterFunction](curlCommand);
        
        res.json({ 
            success: true, 
            code: result,
            language: language 
        });
        
    } catch (error) {
        console.error('转换错误:', error);
        res.status(500).json({ 
            error: `转换失败: ${error.message}` 
        });
    }
});

// 健康检查端点
app.get('/api/health', (req, res) => {
    res.json({ 
        status: 'ok', 
        timestamp: new Date().toISOString(),
        service: 'curlconverter-webui-v3'
    });
});

// 主页路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`🚀 cURL转代码工具服务器已启动`);
    console.log(`📱 访问地址: http://localhost:${PORT}`);
    console.log(`⏹️  停止服务器: Ctrl+C`);
});

module.exports = app;